<?php
namespace app\api\controller;
use app\model\Order as OrderModel;
use app\model\Token as TokenModel;
use app\model\Integral as IntegralModel;
use think\Db;

use app\common\wechat\Pay;


class Order extends Base
{   
    protected $noCheckToken = ['wxPayCallback'];

    /**
     * @Author   CCH
     * @DateTime 2020-05-23T12:10:10+0800
     * @return   数据列表
     */
    public function index(){
        $user_id = $this->login_user['user_id'];
        $map_params = [
            ['key'=>'status','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        $map[] = ['user_id','=',$user_id];

        $model = new OrderModel();
        $page_param = ['page'=>input('page_index',1),'list_rows'=>input('page_size',10)];
        $list = $model->where($map)->order('id desc')->paginate($page_param)->toarray();
        foreach ($list['data'] as $k => $vo) {
            $list['data'][$k]['goods_content'] = json_decode($vo['goods_content'],true);
        }
        return apiResult('2000','获取成功',$list);
    }

    /**
     * 获取详情
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function read($id){
        $user_id = $this->login_user['user_id'];
        $model = new OrderModel();
        $data = $model->where('id',$id)->find();
        if (!empty($data)) {
            $data['goods_content'] = json_decode($data['goods_content'],true);
        }
        
        return apiResult('2000','获取成功',$data);
    }




    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function save(){
        $user_id = $this->login_user['user_id'];

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        $fields = [
            'must'=>['wx_goods_id','sku','num'],
            'nomust'=>[]
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            return apiResult('5000',$params['error_msg']);
        }
        if (empty($params['num']) || $params['num'] < 1) {
            $params['num'] = 1;
        }
        

        $data = Db::name('wx_goods')->where('id',$params['wx_goods_id'])->find();
        if ($data['status'] != 1) {
            // return apiResult('5000','商品已下架');
        }
        $skus = json_decode($data['skus'],true);
        $sku = $skus[$params['sku']];

        if ($sku['stock'] < $params['num']) {
            return apiResult('5000','库存不足');
        }
        
        Db::startTrans();
        try{
            $save_data = [
                'user_id'=>$user_id,
                'order_sn'=>uuidCreate(),
                'wx_goods_id'=>$params['wx_goods_id'],
                'goods_content'=>json_encode($data),
                'goods_type'=>$data['type'],
                'sku'=>$sku['name'],
                'price'=>$sku['price'],
                'total_price'=>$sku['price']*$params['num'],
                'num'=>$params['num'],
                'ctime'=>time()
            ];
            // 如果是积分商品，再做处理
            if ($data['type'] == 1) {
                $user_integral = Db::name('user')->where('id',$user_id)->value('integral');
                if ($user_integral < $save_data['total_price']) {
                    throw new \Exception("积分不足，无法兑换"); 
                }
                $save_data['status'] = 1;

                if ( !IntegralModel::saveData([
                    'user_id'=>$user_id,
                    'remark'=>'兑换商品：'.$data['name'],
                    'amount'=>-$save_data['total_price'],
                    'type'=>3
                ]) ) {
                    throw new \Exception("积分更新失败，请重试"); 
                }
            }

            // 减少库存
            $skus[$params['sku']]['stock'] = $sku['stock'] - $params['num'];
            Db::name('wx_goods')->where('id',$params['wx_goods_id'])->update([
                'skus'=>json_encode($skus,JSON_UNESCAPED_UNICODE)
            ]);


            $model = new OrderModel();
            if ( !$id = $model->insertGetId($save_data) ) {
                throw new \Exception("下单失败，请重试"); 
            }

            // 更新成功 提交事务
            Db::commit();
            return apiResult('2000','下单成功',$id);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    /**
     * 小程序支付
     * @Author   cch
     * @DateTime 2020-05-26T17:22:00+0800
     * @param    $save_data 保存的数据
     * @return   提交结果
     */
    public function wxPay($id){
        $model = new OrderModel();
        $order = $model->where('id',$id)->find();
        if (empty($order) || $order['status'] != 0) {
            return apiResult('5000','该订单无法支付');
        }
        $uinfo = Db::name('user')->where('id',$order['user_id'])->find();
        $openid = $uinfo['openid'];

        if (empty($openid)) {
            return apiResult('5000','openid为空');
        }
        $goods = json_decode($order['goods_content'],true);

        $price = $order['total_price'];
        // $price = 0.01;

        $config = config('config.wxpay');
        $appId = $config['appid'];
        $mchId = $config['mchid'];
        $payKey = $config['paykey'];
        // $notify_url = request()->domain().'/index.php/index/order/wxPayCallback';
        $notify_url = url('wxPayCallback',[],'',true);

        $pay = new Pay($appId, $mchId, $payKey);
        $result = $pay->order($order['order_sn'],$price,$openid,$goods['name'].'商品支付','',2,$notify_url);
        if ($result['status'] == 1) {
            return apiResult('2000','提交成功',$result['data']);
        }else{
            return apiResult('5000',$result['msg']);
        }
    }

    public function wxPayCallback(){
        $xml = file_get_contents('php://input');
        Db::name('test')->insert([
            'content'=>$xml
        ]);
        $params = xmlToArray($xml);
        
        if($params['result_code']=='SUCCESS' && $params['return_code']=="SUCCESS"){
            $order_sn = $params['out_trade_no'];
            $data = Db::name('order')->where('order_sn',$order_sn)->find();

            if ($data['status'] != 0) {
                exit();
            }
            
            $save_data = ['status'=>1,'trade_no'=>$params['transaction_id'],'pay_time'=>time()];
            if ( Db::name('order')->where('id',$data['id'])->update($save_data) !== false ) {
                // $uinfo = Db::name('user')->where('id',$data['user_id'])->find();
                // $user_data = ['role'=>1];
                // if ($uinfo['vip_time'] > date('Y-m-d H:i:s')) {
                //     $vip_time = strtotime($uinfo['vip_time']) + (3600 * 24 * $data['days']);
                //     $user_data['vip_time'] = date('Y-m-d H:i:s',$vip_time);
                // }else{
                //     $vip_time = time() + (3600 * 24 * $data['days']);
                //     $user_data['vip_time'] = date('Y-m-d H:i:s',$vip_time);
                // }
                // Db::name('user')->where('id',$data['user_id'])->update($user_data);

                // // 发送小程序通知
                // $openid = Db::name('user')->where('id',$data['user_id'])->value('openid');
                // $notify_data = [
                //     "name1" => [
                //         "value"=> Db::name('vip_rule')->where('id',$data['vip_rule_id'])->value('name')
                //     ],
                //     "date2" => [
                //         "value"=> date('Y年m月d日')
                //     ],
                //     "thing3" => [
                //         "value"=> $data['days'].'天'
                //     ],
                //     "thing4" => [
                //         "value"=> '可享受多项会员优惠'
                //     ]
                // ];
                // $notify_status = \app\common\wechat\Util::sendUniformMessage($openid,'9kEY6F_TcoHhkpacKYOIr5ry25xPhtT2xz3dcczFe7U',$notify_data,'/pages/mine/mine');
            }
            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }
        return '';
    }
  

    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function finish($id){
        $model = new OrderModel();
        $data = $model->where('id',$id)->find();
        if ($data['status'] != 2) {
            return apiResult('5000','订单状态不符');    
        }

        $model->where('id',$id)->update(['status'=>10]);
        
        return apiResult('2000','操作成功');
    }


}
